﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Smt.Asm.Api.Helper
{
    public class StringHelper
    {
        /// <summary>
        /// 过滤Html字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ConvertHtmlContent(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Replace("<", "&lt;");
                str = str.Replace(">", "&gt;");
            }

            return str;
        }

        /// <summary>
        /// 过滤SQL注入字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ConvertSQLContent(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Replace("；", ";");
                str = str.Replace("‘", "'");
                str = str.Replace("’", "'");
                str = str.Replace("“", "\"");
                str = str.Replace("”", "\"");
                str = str.Replace("：", ":");
                //str = str.Replace(" ", "");
                str = str.Replace("，", ",");
                str = ConvertHtmlContent(str);
            }

            return str;
        }

        /// <summary>
        /// 获取安全的请求参数（过滤Html，SQL等注入）
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetSafeRequestParam(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = ConvertSQLContent(str);
                str = ConvertHtmlContent(str);
            }

            return str;
        }

        /// <summary>
        /// 取得Post数据
        /// </summary>
        /// <param name="paramName"></param>
        /// <returns></returns>
        public static string GetPost(string paramName)
        {
            string paramValue = "";

            if (HttpContext.Current.Request.Form[paramName] != null)
            {
                paramValue = HttpContext.Current.Request.Form[paramName];
            }

            return paramValue;
        }

        /// <summary>
        /// 取得Get数据
        /// </summary>
        /// <param name="paramName"></param>
        /// <returns></returns>
        public static string GetQuery(string paramName)
        {
            string paramValue = "";

            if (HttpContext.Current.Request.QueryString[paramName] != null)
            {
                paramValue = HttpContext.Current.Request.QueryString[paramName];
            }

            return paramValue;
        }

        /// <summary>
        /// 取得Get/Post数据
        /// </summary>
        /// <param name="paramName"></param>
        /// <returns></returns>
        public static string GetRequest(string paramName)
        {
            string paramValue = "";

            if (HttpContext.Current.Request.RequestType.ToLower() == "get")
            {
                paramValue = GetQuery(paramName);
            }
            else
            {
                paramValue = GetPost(paramName);
            }

            return paramValue;
        }

        public static string GetHttpRequestParams()
        {
            string sData = "";
            try
            {
                Encoding encoding = Encoding.GetEncoding("utf-8");
                Stream instream = HttpContext.Current.Request.InputStream;
                var bytes = new byte[instream.Length];
                instream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始
                instream.Seek(0, SeekOrigin.Begin);
                sData = encoding.GetString(bytes);
            }
            catch
            {
                sData = "";
            }
            return sData;
        }

        public static string GetHttpRequestParams(Stream instream)
        {
            string sData = "";
            try
            {
                Encoding encoding = Encoding.GetEncoding("utf-8");
                var bytes = new byte[instream.Length];
                instream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始
                instream.Seek(0, SeekOrigin.Begin);
                sData = encoding.GetString(bytes);
            }
            catch
            {
                sData = "";
            }
            return sData;
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetMd5String(string str)
        {
            // First we need to convert the string into bytes, which
            // means using a text encoder.
            byte[] unicodeText = Encoding.UTF8.GetBytes(str);

            // Now that we have a byte array we can ask the CSP to hash it
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(unicodeText);

            // Build the final string by converting each byte
            // into hex and appending it to a StringBuilder
            var sb = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("x2"));
            }

            // And return it
            return sb.ToString();
        }


        /// <summary>
        /// 获取新的Guid
        /// </summary>
        /// <returns></returns>
        public static string GetGuidString()
        {
            return Guid.NewGuid().ToString().Replace("-", "").Replace("{", "").Replace("}", "").ToLower();
        }


        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetTimeStemp()
        {
            TimeSpan ts = DateTime.Now - Convert.ToDateTime("1970-01-01");
            return (long)ts.TotalSeconds;
        }

        public static DateTime LongToDate(ulong filecreationtime)
        {
            string strDate = "";
            try
            {
                long f = Convert.ToInt64(filecreationtime);
                DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
                long lTime = f * 10 * 1000000;
                var toNow = new TimeSpan(lTime);

                strDate = dtStart.Add(toNow).ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception ex)
            {
            }

            return Convert.ToDateTime(strDate);
        }

        #region 获取单个汉字的首写拼音字母

        /// <summary>
        /// 获取单个汉字的首写拼音字母
        /// </summary>
        /// <param name="cn"></param>
        /// <returns></returns>
        public static string getSpell(string cn)
        {
            byte[] arrCN = Encoding.Default.GetBytes(cn);
            if (arrCN.Length > 1)
            {
                int area = arrCN[0];
                int pos = arrCN[1];
                int code = (area << 8) + pos;
                int[] areacode =
                    {
                        45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324,
                        49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980,
                        53689, 54481
                    };
                for (int i = 0; i < 26; i++)
                {
                    int max = 55290;
                    if (i != 25) max = areacode[i + 1];
                    if (areacode[i] <= code && code < max)
                    {
                        return Encoding.Default.GetString(new[] { (byte)(65 + i) });
                    }
                }
                return cn;
            }
            else return cn;
        }

        #endregion

        #region 获取汉字字符串的首写英文字母

        /// 获取汉字字符串的首写英文字母
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetStringSpell(string str)
        {
            char[] chars = str.ToCharArray();
            string result = "";
            if (chars.Length > 1)
            {
                for (int i = 0; i < chars.Length; i++)
                {
                    result += getSpell(chars[i].ToString());
                }
            }
            else if (chars.Length == 1)
            {
                result = getSpell(str);
            }

            return result.ToUpper();
        }

        #endregion
    }
}